@use 'config';
// BEM support Func
@function selectorToString($selector) {
	$selector: inspect($selector);
	$selector: str-slice($selector, 2, -2);
	@return $selector;
}

@function containsModifier($selector) {
	$selector: selectorToString($selector);

	@if str-index($selector, $modifier-separator) {
		@return true;
	} @else {
		@return false;
	}
}

@function containWhenFlag($selector) {
	$selector: selectorToString($selector);

	@if str-index($selector, '.' + $state-prefix) {
		@return true;
	} @else {
		@return false;
	}
}

@function containPseudoClass($selector) {
	$selector: selectorToString($selector);

	@if str-index($selector, ':') {
		@return true;
	} @else {
		@return false;
	}
}

@function hitAllSpecialNestRule($selector) {
	@return containsModifier($selector) or containWhenFlag($selector) or containPseudoClass($selector);
}

// bem('block', 'element', 'modifier') => 't5-block__element--modifier'
@function bem($block, $element: '', $modifier: '') {
	$name: config.$namespace + $common-separator + $block;

	@if $element != '' {
		$name: $name + $element-separator + $element;
	}

	@if $modifier != '' {
		$name: $name + $modifier-separator + $modifier;
	}

	// @debug $name;
	@return $name;
}

// BEM
@mixin b($block) {
	$B: config.$namespace + '-' + $block !global;
	.#{$B} {
		@content;
	}
}

@mixin e($element) {
	$E: $element !global;
	$selector: &;
	$currentSelector: '';
	@each $unit in $element {
		$currentSelector: #{$currentSelector + '.' + $B + $element-separator + $unit + ','};
	}

	@if hitAllSpecialNestRule($selector) {
		@at-root {
			#{$selector} {
				#{$currentSelector} {
					@content;
				}
			}
		}
	} @else {
		@at-root {
			#{$currentSelector} {
				@content;
			}
		}
	}
}

@mixin m($modifier) {
	$selector: &;
	$currentSelector: '';
	@each $unit in $modifier {
		$currentSelector: #{$currentSelector + $selector + $modifier-separator + $unit + ','};
	}

	@at-root {
		#{$currentSelector} {
			@content;
		}
	}
}
